//
//  ScanViewController.m
//  MyProject
//
//  Created by Pei on 16/6/24.
//  Copyright © 2016年 Xiaobo Pei. All rights reserved.
//

#import "ScanViewController.h"
#import "JackTool.h"

#define TABLE_VIEW_RECT_II CGRectMake(0, NAV_HEIGHT, kDeviceWidth, kDeviceHeight-NAV_HEIGHT)
#define WIDTH_BORDER 200
#define TOP_BORDER 160
#define HEIGHT_BORDER 200

static const char *kScanQRCodeQueueName = "ScanQRCodeQueue";

@interface ScanViewController ()
{
    NSMutableDictionary *scanDic;
    NSString *qcodeString;
    
    NSString *currentAction;
}

@end

@implementation ScanViewController


@synthesize typeStr;

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self stopRunning];
}


- (void)viewDidLoad {
    self.navTitle = @"扫描";
    [super viewDidLoad];
    
    scanDic = [NSMutableDictionary dictionaryWithCapacity:3];
    
    upOrdown = NO;
    num =0;
    _line = [[UIImageView alloc] initWithFrame:CGRectMake((320 - WIDTH_BORDER)/2 + 5, TOP_BORDER, WIDTH_BORDER - 10, 2)];
    _line.image = [UIImage imageNamed:@"lineBar"];
    [self.view addSubview:_line];
    
    
    [self initBorderWithView:self.view];
    
    self.view.backgroundColor = [UIColor blackColor];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    UIButton *menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [menuButton setBackgroundImage:[UIImage imageNamed:@"01back"] forState:UIControlStateNormal];
    [menuButton setBackgroundImage:[UIImage imageNamed:@"01back"] forState:UIControlStateHighlighted];
    [menuButton addTarget:self  action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    menuButton.frame = CGRectMake(0.0f, 0.0f, 22.0f, 22.0f);
    UIBarButtonItem *revealButton = [[UIBarButtonItem alloc] initWithCustomView:menuButton];
    self.navigationItem.leftBarButtonItem = revealButton;
    
    [self setupCamera];
    [self startRunning];
}

- (void)backButtonAction:(UIButton *)button
{
    [timer invalidate];
    
    CATransition *transition = [CATransition animation];
    transition.duration = 0.3;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    transition.type = kCATransitionReveal;
    transition.subtype = kCATransitionFromBottom;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    [self.navigationController popViewControllerAnimated:NO];
}

-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(_line.frame.origin.x, TOP_BORDER+2*num, _line.frame.size.width, 2);
        if (2*num == 200) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(_line.frame.origin.x, TOP_BORDER+2*num, _line.frame.size.width, 2);
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
}

- (void)setupCamera
{
    /*
    if (_device != nil) {
        return;
    }
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    if (!_device) {
        
        NSLog(@"No video camera on this device!"); return;
    }
    
    NSError *error;
    CGPoint point = CGPointMake(0.5f, 0.5f);
    
    
    if ([_device isFocusModeSupported:AVCaptureFocusModeAutoFocus] &&
        [_device isFocusPointOfInterestSupported])
    {
        if ([_device lockForConfiguration:&error]) {
            [_device setFocusPointOfInterest:point];
            [_device setFocusMode:AVCaptureFocusModeAutoFocus];
            [_device unlockForConfiguration];
        } else {
            NSLog(@"Error: %@", error);
        }
    }
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc] init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    // 条码类型 AVMetadataObjectTypeQRCode
    
    // Session
    _session = [[AVCaptureSession alloc] init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeAztecCode,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeCode39Mod43Code];
    
    CGRect frame = TABLE_VIEW_RECT_II;
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame = frame;
    [self.view.layer insertSublayer:self.preview atIndex:0];
    */
    
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        //无权限
        UIAlertView *showAlertView = [[UIAlertView alloc] initWithTitle:@"无法访问相机" message:@"请前往\"设置\",设置允许App访问\"相机\"" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [showAlertView show];
        return;
    }
    
    // 获取 AVCaptureDevice 实例
    NSError * error;
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 初始化输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        //return NO;
    }
    // 创建会话
    _session = [[AVCaptureSession alloc] init];
    // 添加输入流
    [_session addInput:input];
    // 初始化输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    // 添加输出流
    [_session addOutput:captureMetadataOutput];
    
    CGRect frame = TABLE_VIEW_RECT_II;
    
    // 创建dispatch queue.
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create(kScanQRCodeQueueName, NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    // 设置元数据类型 AVMetadataObjectTypeQRCode
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    // 创建输出对象
    _preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_session];
    [_preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_preview setFrame:frame];
    //[self.view.layer addSublayer:_preview];
    [self.view.layer insertSublayer:self.preview atIndex:0];
    // 开始会话
    [_session startRunning];
}

- (void)startRunning {
    if (_running)
        return;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    [_session startRunning];
}

- (void)stopRunning {
    [_session stopRunning];
    [timer invalidate];
}

- (void)viewWillLayoutSubviews
{
    _preview.frame = self.view.bounds;
    // update meta data scan rect
    CGRect metadataRect = [_preview metadataOutputRectOfInterestForRect:CGRectMake(10, TOP_BORDER - 50, WIDTH_BORDER + 100, HEIGHT_BORDER + 100)];
    _output.rectOfInterest = metadataRect;
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
#pragma mark-  解析扫描后的数据
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0){
        _running = YES;
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        qcodeString = metadataObject.stringValue;
        NSLog(@"======qcodeString%@", qcodeString);
        if ([qcodeString hasPrefix:@"project://"]) {
            [self stopRunning];
            NSArray *tempArray = [qcodeString componentsSeparatedByString:@"//"];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (tempArray != nil && tempArray.count >= 2) {
                    NSString *tempStr = [tempArray objectAtIndex:1];
                    NSDictionary *tempDic = [self parseJSONStringToNSDictionary:tempStr];
                    if ([self.delegate respondsToSelector:@selector(passScanValue:)]) {
                        [self.delegate passScanValue:tempDic];
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                }
            });
            
        }
    }
}

- (void)initBorderWithView:(UIView*)sourceView{
    CGRect frame = sourceView.frame;
    CGSize size = frame.size;
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, TOP_BORDER)];
    [topView setBackgroundColor:[UIColor blackColor]];
    topView.alpha = 0.6;
    [sourceView addSubview:topView];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, TOP_BORDER, (size.width - WIDTH_BORDER)/2, HEIGHT_BORDER)];
    [leftView setBackgroundColor:[UIColor blackColor]];
    leftView.alpha = 0.6;
    [sourceView addSubview:leftView];
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake((size.width+WIDTH_BORDER)/2, TOP_BORDER, (size.width - WIDTH_BORDER)/2, HEIGHT_BORDER)];
    [rightView setBackgroundColor:[UIColor blackColor]];
    rightView.alpha = 0.6;
    [sourceView addSubview:rightView];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, TOP_BORDER + HEIGHT_BORDER, size.width, size.height-TOP_BORDER - HEIGHT_BORDER)];
    [bottomView setBackgroundColor:[UIColor blackColor]];
    bottomView.alpha = 0.6;
    [sourceView addSubview:bottomView];
    
    UIImage *borderImg = [UIImage imageNamed:@"scanborder"];
    UIImageView* view = [[UIImageView alloc] initWithImage:borderImg];
    view.frame = CGRectMake((size.width - WIDTH_BORDER)/2, TOP_BORDER, WIDTH_BORDER, HEIGHT_BORDER);
    [view setBackgroundColor:[UIColor clearColor]];
    [sourceView addSubview:view];
}


-(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
